﻿using UnityEngine;
using System.Collections;

[RequireComponent(typeof(PlayerPhysics))]
public class PlayerController : MonoBehaviour {

	
	public float speed = 1; 
	public float acceleration = 8; 
	
	private float currentSpeed;
	private float targetSpeed;
	private Vector2 movement;
    private tk2dSpriteAnimator anim;
	
	private PlayerPhysics playerPhysics;

	void Start () {
		playerPhysics = GetComponent<PlayerPhysics>();
        anim = GetComponent<tk2dSpriteAnimator>();
	}

	void Update () {
		targetSpeed = Input.GetAxisRaw("Horizontal") * speed;
		currentSpeed = AccelerateTo(currentSpeed, targetSpeed, acceleration);
        
        // Handle mouse input
        // Track position of mouse pointer
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Debug.DrawLine(transform.position, mousePos, Color.white);
        //Vector2 mouseNormal = (new Vector2(mousePos.x, mousePos.y));
        Vector3 playerPos = transform.position;
        playerPos.y += 10;
        playerPos.x -= 4;
        Quaternion playerRot = transform.rotation;
        if(Input.GetButtonDown("Fire1")) {
            // Second vector is the representation of the mouse position
            playerPhysics.Fire(new Vector2(mousePos.x, mousePos.y), mousePos, playerPos, playerRot);
            if (anim.IsPlaying("CharShoot"))
            {
                anim.PlayFromFrame("CharShoot", 3);
            }
            else
            {
                anim.PlayFromFrame("CharShoot", 0);
            }
            audio.Play();
        }

		movement.x = currentSpeed;
		playerPhysics.Move(movement);
	}
	
	// Increments or Decrements current to target by factor of accel
	private float AccelerateTo(float current, float target, float accel) {
		if(current == target) { return current; }
		else {
			float direction = Mathf.Sign(target - current); // Decelerating or accelerating
			current += accel * Time.deltaTime * direction;
			if(direction == Mathf.Sign(target - current)) {
				return current;
			}
			else return target; 
		}
	}
}
